<?php

namespace App\Http\Livewire;

use App\Models\User;
use Livewire\Component;
use App\Supports\Sms\Sms;
use App\Supports\Auth\Wap\WapLogger;

class Auth extends Component
{
	/**
	 * @var null | User
	 */
	public $inviter = null;
	public $inviteString = null;
	
	public $phone = null;
	public $sms_key = null;
	public $sms_code = null;
	
	protected function rules()
	{
		return [
			'phone' => 'required|phone:CN,mobile',
			'sms_key' => 'required|string',
			'sms_code' => 'required|digits:4',
		];
	}
	
	protected function messages()
	{
		return [
			'phone' => '手机号码错误',
			'sms_code' => '验证码错误',
		];
	}
	
	protected $validationAttributes = [
		'sms_key' => '验证码密钥',
		'sms_code' => '验证码',
	];
	
	protected function clean()
	{
		$this->inviter = null;
		$this->inviteString = null;
		$this->phone = null;
		$this->sms_key = null;
		$this->sms_code = null;
	}
	
	public function booted()
	{
		$this->inviter = $this->inviteString
			? inviter()->base()->inviterFromString($this->inviteString) : null;
	}
	
	public function send()
	{
		$this->validate([
			'phone' => 'required|phone:CN,mobile|unique:users,phone'
		]);
		$sent = app(Sms::class)->phone($this->phone)
			->template(config("site.sms.code.template.register_account"))
			->data('code', sms_code())->send();
		$this->sms_key = $sent->first();
		session()->flash('message', '验证短信已发出，请您查收，请勿频繁操作。');
	}
	
	public function submit()
	{
		$this->validate();
		$sms = app(Sms::class);
		$verification = $sms->isSmsDataRight($this->sms_key, $this->phone, $this->sms_code);
		if (!$verification) {
			return $this->addError('sms_code', '验证码错误');
		}
		app(WapLogger::class)->auth($this->phone, $this->inviter);
		app(Sms::class)->cleanCachedDataAfterUsing($this->sms_key);
		$this->clean();
		return session()->flash('message', '注册成功，下载APP开始体验吧！');
	}
	
    public function render()
    {
        return view('livewire.auth');
    }
}
